//定义路由
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter)

//导入页面组件

import Home from '@/views/Home'
import Topic from '@/views/Topic'
import Category from '@/views/Category'
import Car from '@/views/Car'
import User from '@/views/User'
// import Search from '@/views/Search'
// import ProductDetail from '@/views/ProductDetail'
// import Channel from '@/views/Channel'
 //配置路由规则
const routes=[
    {
        path: '/',
        redirect: '/home',  // 重定向:重新指向其它path,会改变网址: Home
    },
    {
        path: '/home',
        component: Home,
        name:'home',
        meta:{
            isshowtanbar:true
        },
        children:[{
            //二级路由
            path: 'search',
            component: ()=>import('@/views/Search'),
            name:'search',
            meta:{
                //meta字段为路由元信息
                isshowtanbar:false
            },
        }]
    },
    {
        path: '/topic',
        component:Topic,
        name:'topic',
        meta:{
            isshowtanbar:true
        },
    },
    {
        path: '/category',
        component: Category,
        name:'category',
        meta:{
            isshowtanbar:true
        },
    },
    {
        path: '/car',
        component: Car,
        name:'car',
        meta:{
            isshowtanbar:true
        },
    },
    {
        path: '/user',
        component: User,
        name:'user',
        meta:{
            isshowtanbar:true
        },
    },
    {
        path: '/productdetail',
        component:()=>import('@/views/ProductDetail'),
        name:'productdetail',
        meta:{
            isshowtanbar:false
        },
    },
    {
        path: '/Channel',
        component:()=>import('@/views/Channel'),
        name:'Channel',
        meta:{
            isshowtanbar:false
        },
    }
    
]

//创建路由实例对象
const router=new VueRouter({
    mode:'history',
    routes
})



//监控所有路由导航的前置首位
router.beforeEach((to, from, next) => {
    // 有token就表示已经登录
    let token = localStorage.getItem('token')
    let userinfo = localStorage.getItem('userinfo')
    if (to.path == '/car') {
        
    //如果有token信息就跳转
        if (token||userinfo) {
            next(); // 放心
        } else {
            Vue.prototype.$toast('赶紧登陆');
            // 定时器
            setTimeout(() => {
                next("/user");  // 强制去到对应的路由
            }, 1000);
        }
    } else {
        //其他直接访问
        next()
    }
})
//导出
export default router